package de.fuberlin.inf.alp3.ue01;

public class StringQueue implements Queue<String> {
    protected Cell first;
    protected Cell last;

    protected class Cell {
        String value;
        Cell next;
        Cell previous;
        Cell (String value) {
            this.value = value;
        }
        public Cell next() {
            return next;
        }
        public String toString() {
            return value;
        }
    }

    public StringQueue() {
        first = last = null;
    }

    @Override
    public void append(String s) {
        Cell neu = new Cell(s);
        if (this.first == null) {
            this.first = this.last = neu;
        } else {
            neu.previous = this.last;
            neu.previous.next = neu;
            this.last = neu;
        }
    }

    public void insert(String s) {
        Cell neu = new Cell(s);
        if (this.first == null) {
            this.first = this.last = neu;
        } else {
            neu.next = this.first;
            this.first = neu;
            neu.next.previous = neu;
        }
    }

    @Override
    public int length() {
        if (this.first == null)
            return 0;

        int laenge = 0;
        for (Cell current = this.first; current != null; current = current.next)
            laenge++;
        return laenge;
    }

    @Override
    public String remove() throws QueueUnderflow {
        if (this.first == null)
            throw new QueueUnderflow("There are no more items in queue.");
        String first = this.first.value;
        if (this.first == this.last) {
            this.first = this.last = null;
            return first;
        }
        this.first = this.first.next;
        this.first.previous = null;
        return first; 
    }
}